package org.luxor.common.netty.jdk.aio.client.handler;

import org.luxor.common.netty.jdk.aio.client.AsyncTimeClientHandler;
import org.luxor.commons.core.utils.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

/**
 * 响应 服务端消息
 *
 * @author Mr.yan @date 2023/9/3
 */
public class ClientWriteCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
    private static final Logger log = LoggerFactory.getLogger(ClientWriteCompletionHandler.class);

    private AsyncTimeClientHandler attachment;

    public ClientWriteCompletionHandler(AsyncTimeClientHandler attachment) {
        if (attachment != null) {
            this.attachment = attachment;
        }
    }

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        if (buffer.hasRemaining()) {
            attachment.getClientAsyncSocketChannel().write(buffer, buffer, this);
        } else {
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            attachment.getClientAsyncSocketChannel().read(readBuffer, readBuffer, new ClientReadCompletionHandler(attachment));
        }
    }


    @Override
    public void failed(Throwable exc, ByteBuffer buffer) {
        log.error("读取对端消息，失败", exc);
        IoUtils.closeQuietly(attachment.getClientAsyncSocketChannel());
        attachment.getLatch().countDown();
    }
}
